package com.shihb.chapter02function

/**
 * 隐式转换的介绍
 */
object Demo06Implicit {
  def main(args: Array[String]): Unit = {
    //1、编写一个隐式函数转成Double->Int转换
    implicit def f1(d: Double): Int = {
      d.toInt
    }

    /*
      private final int f1$1(double d)
      {
        return (int)d;
      }
     */
    val num: Int = 3.4 //f1$1(3.4D)
    println(num)

    // 2、动态扩展类的功能
    implicit def f2(mysql: Mysql): ExpandMysqlClass = {
      new ExpandMysqlClass
    }

    val mysql = new Mysql
    mysql.delete //f2$1(mysql)
    // 3、隐式值隐式参数
    implicit val str: String = "jack" //这个时隐式值
    //implicit name:String      name就是隐式参数
    def hello(implicit name: String = "tom"): Unit = {
      println(name + " hello")
    }

    hello

    // 4、隐式类
    //    当我们在隐式类的作用域范围，创建参数的实例，隐式类就会生效，这个工作仍然是编译器完成
    implicit class DB1(val m: Mysql) { //只要在作用范围内创建Mysql，隐式类就生效了
      def addSuffix(): String = {
        m + "scala"
      }
    }
    mysql.addSuffix()//DB1(mysql)
  }
}

class Mysql {
  def insert: Unit = {
    println("insert...")
  }
}

// 要给Mysql新增功能
class ExpandMysqlClass {
  def delete: Unit = {
    println("delete...")
  }

}
